//
//  MobileVehicleRegPlates.m
//  LPlates.app
//
//  Created by Andreas Schwelling on 23.11.07.
//	http://www.andi.de/licenseplates/
//
//  Released under the GNU General Public License.
//  See LICENSE for details.
//
//  Use at your own risk.



#import "MobileVehicleRegPlates.h"



static MobileVehicleRegPlates *sharedInstance;

@implementation MobileVehicleRegPlates

+ (MobileVehicleRegPlates *)sharedInstance
{
	if (!sharedInstance)
		sharedInstance = [[MobileVehicleRegPlates alloc] init];
	
	return sharedInstance;
}

- (void) applicationWillTerminate {
	
}

- (void) applicationResume:(struct __GSEvent *) event {
}

- (void) applicationSuspend:(struct __GSEvent *) event {
	[self terminateWithSuccess];
}

- (void) applicationWillSuspend
{
	
}




- (void) applicationDidFinishLaunching: (id) unused
{
	// init the singleton
	sharedInstance = self;
	
	_appLibraryPath = [[self userLibraryDirectory] stringByAppendingPathComponent: @"LPlates"];
	_appSettingsPath = [_appLibraryPath stringByAppendingPathComponent: @"Settings.plist"];
	[[NSFileManager defaultManager] createDirectoryAtPath: _appLibraryPath attributes: nil];
	[_appSettingsPath retain];
	
	if(![[NSFileManager defaultManager] fileExistsAtPath: _appSettingsPath]) NSLog(@"no plist");
	
	//  mainWindow = [[UIWindow alloc] initWithContentRect: [UIHardware
	//		    fullScreenApplicationContentRect]];
	
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	transitionView = [[UITransitionView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	
	mainView = [[UIView alloc] initWithFrame: rect];
	
	
	
	[mainView addSubview:transitionView];
	
	mainWindow = [[UIWindow alloc] initWithContentRect:rect];
	[mainWindow setContentView:mainView];
	
	
	
	[mainWindow orderFront:self];
	[mainWindow makeKey:self];
	[mainWindow _setHidden:NO];
	
	
	aboutSheet = [ [ UIAlertSheet alloc ] initWithFrame:
				  CGRectMake(0, 240, 320, 240) ];
	[ aboutSheet setTitle:@"LicensePlates" ];
	[ aboutSheet setBodyText:@"Version 0.3.1\ndeveloped by sAkYa\n\nNot a very exciting one - mainly just for futzing with UIKit functions :)\n\nMaybe you can use it somehow." ];
	[ aboutSheet addButtonWithTitle:@"OK" ];
	[ aboutSheet addButtonWithTitle:@"Contact"]; 
	[ aboutSheet addButtonWithTitle:@"URL"]; 
	[ aboutSheet setDelegate: self ];
	
	
	
	whatsSheet = [ [ UIAlertSheet alloc ] initWithFrame:
				  CGRectMake(0, 240, 320, 240) ];
	[ whatsSheet setTitle:@"LicensePlates" ];
	[ whatsSheet setBodyText:@"Just a petty application that will give you some information on the abbreviations used on car license plates in some countries.\n\nChoose the country a license plate belongs to and pick out the relating code - or search for it with the 'Search' button -- you will see the full name of the county or city along with some additional information.\nEnjoy!" ];
	[ whatsSheet addButtonWithTitle:@"OK" ];
	[ whatsSheet addButtonWithTitle:@"donate" ];
	
	[ whatsSheet setDelegate: self ];
	
	
  	askupdateSheet = [ [ UIAlertSheet alloc ] initWithFrame:
					  CGRectMake(0, 240, 320, 240) ];
	[ askupdateSheet setTitle:@"Update" ];
	[ askupdateSheet setBodyText:@"Fetch newest data from server?" ];
	[ askupdateSheet addButtonWithTitle:@"OK" ];
	[ askupdateSheet addButtonWithTitle:@"Cancel" ];
	[askupdateSheet setAlertSheetStyle:1	];
	[ askupdateSheet setDelegate: self ];
	
	//[ updateSheet addButtonWithTitle:@"Cancel" ];
	// [ updateSheet addButtonWithTitle:@"OK" ];
	
  	updateSuccessSheet = [ [ UIAlertSheet alloc ] initWithFrame:
						  CGRectMake(0, 240, 320, 240) ];
	[ updateSuccessSheet setTitle:@"Update" ];
	[ updateSuccessSheet setBodyText:@"Update sucessful!\n" ];
	[updateSuccessSheet setAlertSheetStyle:1	];
	
  	updateSheet = [ [ UIAlertSheet alloc ] initWithFrame:
				   CGRectMake(0, 240, 320, 240) ];
	[ updateSheet setTitle:@"Updating..." ];
	[ updateSheet setBodyText:@"Checking for update\n\n" ];
	//[ updateSheet addButtonWithTitle:@"Cancel" ];
	// [ updateSheet addButtonWithTitle:@"OK" ];
	[ updateSheet setDelegate: self ];
	[updateSheet setAlertSheetStyle:1	];
	progressIndicator = [[UIProgressBar alloc] initWithFrame:CGRectMake(60.0f, 55.0f, 200.0f,50.0f)];
	[updateSheet addSubview:progressIndicator];
	
	[self showCountries:1];
	
	//progress = [[UIProgressHUD alloc] initWithWindow: mainWindow];
	////[progress setText:@"test"];
	//[progress drawRect: CGRectMake(0, 240, 320, 240)];
	//[progress show:YES];
	//[mainView addSubview:progress];
}

- (void)setUpgradeProgress:(int)p
{
	//float prog =  p/updatesize;
	//NSLog(@" progress: %f",p/updatesize);
	
	[progressIndicator setProgress:(float)p/updatesize];
}


- (void) showSearchView
{
	struct CGRect rect1 = [UIHardware fullScreenApplicationContentRect];
	rect1.origin.x = rect1.origin.y = 0.0f;
	searchView = [[SearchView alloc] initWithFrame:CGRectMake(rect1.origin.x, rect1.origin.y, rect1.size.width, rect1.size.height)];
	
	[searchView setDelegate:self];
	
	LKAnimation *myAnimObj = [LKTransition animation];
    [myAnimObj setType: @"pageUnCurl"];
	
    [myAnimObj setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
    
    [myAnimObj setTransitionFlags: 3];
	[myAnimObj setFillMode:@"extended"];
    
	
    [myAnimObj setSpeed: .4 / 1.];
    
    [[mainView _layer] addAnimation: myAnimObj forKey: 0];
	
	//[[self superview]  transition:0 toView:self ];
	
	//[mainView addSubview:searchView];
	//[[transitionView superview]   transition:0 toView:searchView ];
	
	[transitionView transition:0 toView:searchView];
}


- (void) hideSearchView:(int)mode {
	
	if (mode == 1) {
		
		//[detailView addSubview:transitionView];
		LKAnimation *myAnimObj = [LKTransition animation];
		[myAnimObj setType: @"pageCurl"];
		
		[myAnimObj setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
		//edge aliasing?
		[myAnimObj setTransitionFlags: 3];
		[myAnimObj setFillMode:@"extended"];
		// setDuration doesn't work here for me, 
		// setSpeed param = 0.25 / seconds
		[myAnimObj setSpeed: .4 / 1.];
		
		[[mainView _layer] addAnimation: myAnimObj forKey: 0];
		
		[transitionView transition:0 fromView:searchView toView:countyView];
		[mainWindow setContentView: mainView];
		[searchView release]; 
	} else {
		
		[transitionView transition:2 fromView:searchView toView:countryView];
		[mainWindow setContentView: mainView];
		[searchView release];
		
	}
	
}

- (void) showCountries:(int)trans {
	struct CGRect rect1 = [UIHardware fullScreenApplicationContentRect];
	rect1.origin.x = rect1.origin.y = 0.0f;
	
	countryView = [[CountryList alloc] initWithFrame:CGRectMake(rect1.origin.x, rect1.origin.y, rect1.size.width, rect1.size.height)];
	
	
	[transitionView transition:trans toView:countryView];
}

- (void) showCountryEdit{
	
	
	countryEditView = [[CountryEditView alloc] initWithFrame:CGRectMake(0.0f, 45.0f, 320.0f, 415-45.0f)];
	
	
	[mainView addSubview:countryEditView];
	UIAlphaAnimation* alpha = [[UIAlphaAnimation alloc] initWithTarget: countryEditView];
	[alpha setStartAlpha: 0.0f];
	[alpha setEndAlpha: 1.0f];
	[[[UIAnimator alloc] init] addAnimation:alpha withDuration:.8 start:YES];
	
	BOOL showSheet = true;
	id plistval = [self getPListParam:@"showEditDescript"];
	if (plistval != nil) showSheet = [plistval boolValue];
	
	if (showSheet) {
		helpSheet = [ [ UIAlertSheet alloc ] initWithFrame: CGRectMake(0, 240, 320, 240) ];
		[ helpSheet setTitle:@"Edit countries" ];
		[ helpSheet setBodyText:@"Delete unwanted countries by using the red 'Delete' button. Add favoured countries with the green 'Add' button - or just drag them to the 'Visible' or 'Hidden' sections." ];
		[ helpSheet addButtonWithTitle:@"OK" ];
		[ helpSheet addButtonWithTitle:@"Don't show again" ];
		[helpSheet setAlertSheetStyle:1	];
		[ helpSheet setDelegate: self ];
		[ helpSheet presentSheetInView: mainView ];
	}
	
}



- (void) hideCountryEdit{
	
	
	UIAlphaAnimation* alpha = [[UIAlphaAnimation alloc] initWithTarget: countryEditView];
	[alpha setStartAlpha: 1.0f];
	[alpha setEndAlpha: 0.0f];
	[[[UIAnimator alloc] init] addAnimation:alpha withDuration:.8 start:YES];
	
	[countryEditView release];
}

- (void) showCounties:(int)trans {
	
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	countyView = [[CountyList alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	[countyView setDelegate: self];
	
	[transitionView transition:trans toView:countyView];
	
	
}


- (void) showDetails:(int)trans {
	
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	detailView = [[DetailsView alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
	[detailView setDelegate: self];
	
	
	[transitionView transition:trans toView:detailView];
	
	
}

- (void) hideCountyView {
	
	//[detailView addSubview:transitionView];
	[transitionView transition:2 fromView:countyView toView:countryView];
	[mainWindow setContentView: mainView];
	[countyView release];
}

- (void) setBeforeDetailView:(id)view {
	beforeDetailView = view;
}

- (void) hideDetailView {
	
	//[detailView addSubview:transitionView];
	[transitionView transition:2 fromView:detailView toView:beforeDetailView];
	[mainWindow setContentView: mainView];
	[detailView release];
}

- (void) setCountry:(id)cint {
	countryint = cint;
}

- (id) getCountry {
	return countryint;
}

- (void) setCounty:(id)cint {
	cint = [cint copy];
	[countyint release];
	countyint = cint;
}

- (id) getCounty {
	return countyint;
}

- (void) setDescription:(NSString*)descr {
	descr = [descr copy];
	[descript release];
	descript = descr;
}

- (NSString*) getDescription {
	
	//NSLog(@"descr: %@",descript);
	return descript;
}



- (void) setState:(NSString*)s {
	s = [s copy];
	[state release];
	state = s;
}

- (NSString*) getState {
	
	//NSLog(@"descr: %@",descript);
	return state;
}

- (void) noNewUpdate:(id)p
{
	
	[updateSheet dismiss];
	[ updateSuccessSheet setBodyText:@"Your data is already up-to-date!"];
	[ updateSuccessSheet presentSheetInView: mainView ];
	[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(hideUpdateSucess:) userInfo:nil repeats:NO];
	
}

- (void) checkForUpdate:(id)p
{
	NSString *updatefilename;
	NSString *updateversion;
	NSString *localversion;
	NSDictionary *remotedict;
	
	
	//	[self showUpdateSheet];
	
	localversion = [[self getPListParam:@"dataversion"] intValue];
	remotedict = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:@"http://www.andi.de/downloads/licenseplates/update.plist"]];
	updateversion = [[remotedict objectForKey:@"version"] intValue];
	
	if (!updateversion) {
		[updateSuccessSheet setTitle:@"Error!"];
		[updateSuccessSheet setBodyText:@"Update failed!"];
		[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(dismissUpdateSheet:) userInfo:nil repeats:NO];
		return;
	}
	
	if (!localversion) {
		localversion = 0;
	}
	
	NSLog(@" remote data version: %d",updateversion);
	NSLog(@" local data version: %d",localversion);
	[progressIndicator setProgress:1.0f];
	
	if (updateversion > localversion) {
		
		NSLog(@"newer data, updating");
		
		updatefilename = [remotedict objectForKey:@"filename"];
		NSLog(@"update filename: %@",updatefilename);
		
		updatesize = [[remotedict objectForKey:@"filesize"] intValue];
		
		NSLog(@"update filesize: %d",updatesize);
		[UIView beginAnimations:nil];
		[UIView setAnimationCurve:kUIAnimationCurveEaseInEaseOut];
		[UIView setAnimationDuration:1.75];
		
		[progressIndicator setProgress:0.0f];
		
		
		[UIView endAnimations];
		
		[UIView beginAnimations:nil];
		[UIView setAnimationCurve:kUIAnimationCurveEaseInEaseOut];
		[UIView setAnimationDuration:0.75];
		[updateSheet setBodyText:[NSString stringWithFormat:@"Updating to vol. 0.%d, loading %d kB data\n\n",updateversion, updatesize/1024]];
		[UIView endAnimations];
		
		downloader = [Downloader downloadURL: [@"http://www.andi.de/downloads/licenseplates/" stringByAppendingString:updatefilename] to: @"/Applications/LPlates.app/default.plist" app: self trigger: NO];
		[self setPListParam:[NSNumber numberWithInt: updateversion] key:@"dataversion"];
		[downloader release];
		
	} else {
		
		
		[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(noNewUpdate:) userInfo:nil repeats:NO];
		
		
		
	}
	
	
	
  	
	
}

- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
	
	if (sheet == helpSheet) {
		
		if (button == 2) {
			
			NSLog(@" dont show again");
			[self setPListParam:[NSNumber numberWithBool: NO] key:@"showEditDescript"];
		}
		
	}
	
	if (sheet == askupdateSheet) {
		
		if (button == 1) {
			[progressIndicator setProgress:0.0f];
			[ updateSheet setBodyText:@"Checking for update...\n\n" ];
			[self showUpdateSheet];
			[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(checkForUpdate:) userInfo:nil repeats:NO];
			
		}
		
	}
	else if (sheet == aboutSheet) {
		
		if (button == 2) {
			
			[self openURL:[NSURL URLWithString:@"mailto:andi@andi.de?subject=Regarding%20LicensePlates"]];
			
		}
		else if (button == 3) {
			
			[self openURL:[NSURL URLWithString:@"http://www.andi.de/licenseplates/"]];
			
		}   	
	} else if (sheet == whatsSheet) {
		
		if (button == 2) {
			
			[self openURL:[NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=andreas%40schwelling%2ede&item_name=LPlates%20donation&no_shipping=0&no_note=1&tax=0&currency_code=EUR&bn=PP%2dDonationsBF&charset=UTF%2d8"]];
			
		}
		
	}
	
	[ sheet dismiss ];
}

- (void)showUpdateSheet
{
	[ updateSheet presentSheetInView: mainView ];
}

- (void) showUpdateSuccess:(id)param
{
	[ updateSuccessSheet presentSheetInView: mainView ];
	[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(hideUpdateSucess:) userInfo:nil repeats:NO];
}

- (void) hideUpdateSucess: (id)param 
{
	
	[updateSuccessSheet dismiss];
	[UIView beginAnimations:nil];
	[UIView setAnimationCurve:kUIAnimationCurveEaseInEaseOut];
	[UIView setAnimationDuration:0.75];
	[countryView reloadCountries];
	[UIView endAnimations];
	
}

- (void) setPListParam: (id) param key: (id)keyval
{
	
	NSMutableDictionary* preferencesDict;
	
	if(![[NSFileManager defaultManager] fileExistsAtPath: _appSettingsPath])
	  {	
		  NSLog(@"no plist found, new dict");
		  preferencesDict = [[NSMutableDictionary alloc] init];
		  
	  } else {
		  
		  preferencesDict = [NSDictionary dictionaryWithContentsOfFile: _appSettingsPath];
		  
	  }
	
	[preferencesDict setObject:param forKey:keyval];
	[preferencesDict writeToFile: _appSettingsPath atomically: YES];
}

- (id) getPListParam: (id) key 
{
	
	if(![[NSFileManager defaultManager] fileExistsAtPath: _appSettingsPath])
	  {	
		  NSLog(@"no plist found");
		  return nil;
	  }
	
	NSDictionary* preferencesDict = [NSDictionary dictionaryWithContentsOfFile: _appSettingsPath];
	return [preferencesDict objectForKey:key];
	
}


- (void) saveHiddenCountries
{
	
	[self setPListParam:[countryEditView getHiddenCountries] key:@"hiddenCountries"];
	
}



- (void)hideUpdateSheet:(id)param
{
	
	[updateSheet dismiss];
	[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(showUpdateSuccess:) userInfo:nil repeats:NO];
	
	
}

- (void)dismissUpdateSheet:(int)code
{
	//NSLog(@"code %@",code);
	if (code == 1) {
		[updateSuccessSheet setTitle:@"Error!"];
		[updateSuccessSheet setBodyText:@"Update failed!"];
	}
	[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(hideUpdateSheet:) userInfo:nil repeats:NO];
	
	
	
}

- (void)showAskUpdateSheet
{
	[ askupdateSheet presentSheetInView: mainView ];
}

- (void)showAboutSheet
{
	[ aboutSheet popupAlertAnimated:YES ];
}
- (void)showWhatsSheet
{
	[ whatsSheet popupAlertAnimated:YES ];
}





@end